package com.linmo.loginmanage;

import com.linmo.util.DBUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserManage {

    private static final Logger logger = LoggerFactory.getLogger(UserManage.class);


    //用户注册
    public boolean register( String username, String password) {

        try (Connection connection = DBUtil.getConnection()) {
            // 用户名唯一性校验
            String sql1 = "select * from users where username = ?";
            PreparedStatement statement1 = connection.prepareStatement(sql1);
            statement1.setString(1, username);
            if (statement1.executeQuery().next()) {
                logger.error("用户名已存在");
                return false;
            }

            // 密码加密MD5
            String newPassword = DigestUtils.md5Hex(password.getBytes());

            String sql = "insert into users(username,password) values(?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, newPassword);
            int rows = statement.executeUpdate();
            if (rows > 0) {
                logger.info("注册成功");
                return true;
            } else {
                logger.error("注册失败");
                return false;
            }
        } catch (SQLException e) {
            logger.error("连接失败", e);
            return false;
        }
    }

    // 用户登录
    public boolean login(String username, String password) {
        try (Connection conn = DBUtil.getConnection()) {
            // 对传过来的明文密码进行md5加密
            String newPassword = DigestUtils.md5Hex(password.getBytes());
            if (newPassword.equals("")) {
                logger.error("密码不能为空");
                return false;
            }
            if (username.equals("")) {
                logger.error("用户名不能为空");
                return false;
            }

            String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, newPassword);
            ResultSet rs = statement.executeQuery();
            if (rs.next()) {
                logger.info("登录成功");
                return true;
            }else {
                logger.error("用户名或密码错误");
                return false;
            }
        } catch (SQLException e) {
            logger.error("连接失败", e);
            return false;
        }
    }

    // 删除用户
    public static void deleteUser(int userId) {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "DELETE FROM users WHERE id = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            int rows = pstmt.executeUpdate();
            if (rows > 0) {
                logger.info("删除成功");
            } else {
                logger.error("删除失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    // 修改密码
    public static void changePassword(int userId, String currentPassword, String newPassword) {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "UPDATE users SET password = ? WHERE id = ? AND password = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, newPassword);
            pstmt.setInt(2, userId);
            pstmt.setString(3, currentPassword);
            int rows = pstmt.executeUpdate();
            if (rows > 0) {
                logger.info("修改密码成功");
            } else {
                logger.error("修改密码失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    // 根据用户名获取用户信息
    public static User getUser(String username) {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM users WHERE username = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return new User(rs.getInt("id"), rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
